<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Validation class for validating that an email can be registered in the system.
 * Makes sure that the email does not already exist in the system,
 * and that an user with that email is not already registered
 *
 * @category    RedCross
 * @package     RedCross_Validate
 */
class RedCross_Validate_CanRegister extends Zend_Validate_Abstract
{
    /**
     * Validation failure message key for when
     * the email already exists in the system
     * or an user with that email is already registered
     * @var string
     */
    const EMAIL_NOT_APPLICABLE = 'emailNotApplicable';

    /**
     * Validation failure message template definitions
     * @var array
     */
    protected $_messageTemplates = array(
        self::EMAIL_NOT_APPLICABLE => 'Epostadressen eksisterer ikke i systemet, eller så er en bruker med denne epostadressen allerede registrert'
    );

    /**
     * (non-PHPdoc)
     * @see library/Zend/Validate/Zend_Validate_Interface#isValid($value)
     */
    public function isValid($value)
    {
        $value = (string) $value;
        $this->_setValue($value);

        $record = Doctrine_Query::create()
            ->select('e.id')
            ->from('Core_Model_Email e')
            ->leftJoin('e.Member m')
            ->leftJoin('m.User u')
            ->where('e.address = ?', $value)
            ->addWhere('u.id IS NULL')
            ->fetchOne();

        if (!$record) {
            $this->_error(self::EMAIL_NOT_APPLICABLE);
            return false;
        }
        return true;
    }

}
